package com.thermal.thermal_inspection.aspect;

import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


@Aspect
@Component
public class InternalApiAspect {

    // 拦截所有带有 @InternalApi 注解的方法
    @Around("@annotation(com.thermal.thermal_inspection.annotation.InternalApi)")
    public Object checkInternalAccess(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取当前请求（仅适用于 HTTP 调用场景）
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 2. 从请求头中获取调用方标识（例如 Feign 拦截器设置的头部）
        String caller = request.getHeader("X-Internal-Caller");

        // 3. 验证是否来自合法服务（假设合法调用方是 "feign-client"）
        if (!"feign-client".equals(caller)) {
            throw new RuntimeException("禁止外部访问内部接口！");
        }

        // 4. 放行合法请求
        return joinPoint.proceed();
    }
}
